/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.classes.Ticket;
import com.railway.utils.RestServer;
import com.railway.utils.Toast;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.railway.classes.Staff;



/**
 *
 * @author Moofie
 */
public class Payment extends javax.swing.JDialog {
     private static String[] tickets = new String[Ticket.getNoTickets()];
     private String[] tempTrim = new String[Ticket.getNoTickets()*2];
     private String[] selectedSeat = new String[Ticket.getNoTickets()];
     public static String[] referenceNo = new String[10];
     private StringBuilder sb = new StringBuilder();
     private int x = 0 ;
     private JDialog dialog;
    /**
     * Creates new form Payment
     */
    public Payment(java.awt.Frame parent, boolean modal, JDialog dialog) {
        super(parent, modal);
        initComponents();
        this.dialog = dialog;
        jbtSubmit.setEnabled(true);
        tickets = SeatDialog.getTickets();
        initialize();
        SeatDialog sd = new SeatDialog(null,true);
        jtfAmountPaid.setEditable(true);
        getSelectedSeat();

    }
    
    private void initialize(){
        jtfTickets.setText(""+Ticket.getNoTickets());
        jtfTotal.setText(""+Ticket.getTotal());
        jtfDiscount.setText(""+Ticket.getDiscount());
    }
    
    private void getSelectedSeat(){
        String temp = null;
        for(int i = 0 ; i < Ticket.getNoTickets() ; i++){
            sb.append(tickets[i]);
            sb.append("->");
        }
        temp = sb.toString();
        tempTrim = temp.split("->");
        
        for(int i =0 ; i < tempTrim.length ;i++){
            selectedSeat[x] = tempTrim[i];
            i++;
            x++;
        }
        
    }

    public static String[] getTickets() {
        return tickets;
    }

    public static void setTickets(String[] tickets) {
        Payment.tickets = tickets;
    }

    
    
    public static String[] getReferenceNo() {
        return referenceNo;
    }

    public static void setReferenceNo(String[] referenceNo) {
        Payment.referenceNo = referenceNo;
    }
    
    
    
    public static boolean isNumeric(String str){  
        try{  
            double d = Double.parseDouble(str);  
        }  
        catch(NumberFormatException nfe){  
            return false;  
        }  
        return true;  
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jbtSubmit = new javax.swing.JButton();
        jtfTickets = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jtfDiscount = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jtfTotal = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jtfAmountPaid = new javax.swing.JTextField();
        jtfChange = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);

        jPanel1.setBackground(new java.awt.Color(46, 204, 113));
        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 2, true));
        jPanel1.setOpaque(false);
        jPanel1.setRequestFocusEnabled(false);

        jLabel1.setFont(new java.awt.Font("Calibri Light", 0, 18)); // NOI18N
        jLabel1.setText("Payment");

        jbtSubmit.setText("Confirm");
        jbtSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSubmitActionPerformed(evt);
            }
        });

        jtfTickets.setEditable(false);

        jLabel2.setText("Tickets");

        jLabel4.setText("Discount");

        jtfDiscount.setEditable(false);

        jLabel5.setText("Total");

        jtfTotal.setEditable(false);

        jLabel6.setText("Tender");

        jLabel7.setText("Change");

        jtfChange.setEditable(false);

        jButton2.setText("Back");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(63, 63, 63)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(21, 21, 21)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jtfDiscount)
                                    .addComponent(jtfTotal)
                                    .addComponent(jtfAmountPaid)
                                    .addComponent(jtfChange, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(21, 21, 21)
                                .addComponent(jtfTickets, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfTickets, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtfDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtfTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jtfAmountPaid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jtfChange, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbtSubmit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jbtSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSubmitActionPerformed
        try{
        double total = Double.parseDouble(jtfTotal.getText());
        double amountPaid = Double.parseDouble(jtfAmountPaid.getText());
        double balance = 0;

        if(jtfAmountPaid.getText().length()!=0){
                if(total > amountPaid){
                    Toast.makeText(getParent(), "Amount is lower than total", Toast.LENGTH_LONG).display();
                }else{
                    String a;
                    int status = 500;
                    for(int i = 0 ; i < Ticket.getNoTickets() ; i++){
                        Map<String, Object> data = new HashMap<>();
                        data.put("departureDate", Ticket.getBookedDate());
                        data.put("departure",Ticket.getDepatureTime());
                        data.put("arrival","");
                        data.put("origin",Ticket.getOrigin());
                        data.put("destination",Ticket.getDestination());
                        data.put("classes",Ticket.getClasses().trim());
                        data.put("fare",Ticket.getTicketPrice());
                        data.put("status",Ticket.getStatus());
                        data.put("discountId",Ticket.getDiscountId());
                        data.put("shid",Ticket.getShid());
                        data.put("sshid", Ticket.getShid());
                        data.put("sseatid", tickets[i]);
                        data.put("sreferrenceNo", null);

                        a = RestServer.httpPost("createTicket", data);
                        System.out.println(a);
                    
                        try{
                            JSONObject json = new JSONObject(a);
                            JSONObject ja = json.getJSONObject("content");
                            System.out.println(json.getInt("status"));
                            status = json.getInt("status");
                            referenceNo[i] = ja.getString("referenceNo");

                        }catch(JSONException ex){
                            System.out.println(ex);
                        }
                        System.out.println("NO: "+referenceNo[i]);
                    }
                    
                    Map<String, Object> dataLog = new HashMap<>();
                    dataLog.put("amount", total);
                    dataLog.put("madeBy", Staff.getUid());
                    dataLog.put("type","walk-in");
                    String b = RestServer.httpPost("insertSalesLog", dataLog);
                    System.out.println(b);
                    int statusLog=0;
                    try{
                        JSONObject json = new JSONObject(b);
                        statusLog = json.getInt("status");
                    }catch(JSONException ex){
                        System.out.println(ex);
                    }
                    if(status==200 && statusLog==200){
                        Staff.setTransaction(true);
                        balance = amountPaid - total;
                        jtfChange.setText(""+balance);
                        Toast.makeText(getParent(), "Payment Success", Toast.LENGTH_LONG).display();
                        jbtSubmit.setEnabled(false);
                        TicketPrint ticketPrint = new TicketPrint(null,true,this,dialog);
                        ticketPrint.show();
                    }else{
                        Toast.makeText(getParent(), "Payment Fail\nPlease try again.", Toast.LENGTH_LONG).display();
                    }


                }

        }else{
            Toast.makeText(getParent(), "Please enter paid amount", Toast.LENGTH_LONG).display();
        }
        }catch(NumberFormatException ex){
            Toast.makeText(getParent(), "Amount must be digit", Toast.LENGTH_LONG).display();
        }
    }//GEN-LAST:event_jbtSubmitActionPerformed

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbtSubmit;
    private javax.swing.JTextField jtfAmountPaid;
    private javax.swing.JTextField jtfChange;
    private javax.swing.JTextField jtfDiscount;
    private javax.swing.JTextField jtfTickets;
    private javax.swing.JTextField jtfTotal;
    // End of variables declaration//GEN-END:variables
}
